#!/usr/bin/env python3
"""
验证Web界面路由配置
"""
import sys
import os
from fastapi import FastAPI
from fastapi.routing import APIRoute

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

def check_routes():
    """检查所有路由配置"""
    print("检查Web界面路由配置...")
    
    try:
        from main import app
        
        # 获取所有路由
        routes = []
        for route in app.routes:
            if isinstance(route, APIRoute):
                routes.append({
                    "path": route.path,
                    "methods": list(route.methods),
                    "name": route.name,
                    "endpoint": route.endpoint.__name__ if hasattr(route.endpoint, '__name__') else str(route.endpoint)
                })
        
        # 检查必需的路由
        required_routes = {
            "GET /": "根路径",
            "GET /web/": "Web界面根路径",
            "GET /web/login": "登录页面",
            "GET /web/dashboard": "仪表板页面",
            "GET /web/upload": "上传页面",
            "GET /web/tasks": "任务页面",
            "GET /web/slicing": "切片页面",
            "GET /web/users": "用户管理页面",
            "GET /web/logs": "日志页面",
            "GET /web/settings": "设置页面",
            "POST /api/v1/auth/login": "登录API",
            "GET /api/v1/tasks/my-tasks": "用户任务API",
            "GET /api/v1/admin/users": "用户管理API",
            "GET /api/v1/admin/settings": "设置管理API",
        }
        
        print("\n检查必需路由:")
        missing_routes = []
        for route_pattern, description in required_routes.items():
            method, path = route_pattern.split(" ", 1)
            found = False
            
            for route in routes:
                if route["path"] == path and method in route["methods"]:
                    print(f"[OK] {route_pattern} - {description}")
                    found = True
                    break
            
            if not found:
                print(f"[ERROR] {route_pattern} - {description} (未找到)")
                missing_routes.append(route_pattern)
        
        # 显示所有路由
        print(f"\n所有路由 ({len(routes)} 个):")
        for route in sorted(routes, key=lambda x: x["path"]):
            methods = ", ".join(sorted(route["methods"]))
            print(f"  {methods} {route['path']} -> {route['endpoint']}")
        
        if missing_routes:
            print(f"\n[ERROR] 缺少 {len(missing_routes)} 个必需路由")
            return False
        else:
            print(f"\n[OK] 所有必需路由都存在")
            return True
            
    except Exception as e:
        print(f"[ERROR] 检查路由时出错: {e}")
        return False

def check_templates():
    """检查模板文件"""
    print("\n检查模板文件...")
    
    template_files = [
        "templates/base.html",
        "templates/login.html", 
        "templates/dashboard.html",
        "templates/upload.html",
        "templates/tasks.html",
        "templates/slicing.html",
        "templates/users.html",
        "templates/logs.html",
        "templates/settings.html"
    ]
    
    missing_files = []
    for file_path in template_files:
        if os.path.exists(file_path):
            print(f"[OK] {file_path}")
        else:
            print(f"[ERROR] {file_path} (未找到)")
            missing_files.append(file_path)
    
    if missing_files:
        print(f"\n[ERROR] 缺少 {len(missing_files)} 个模板文件")
        return False
    else:
        print(f"\n[OK] 所有模板文件都存在")
        return True

def check_static_files():
    """检查静态文件"""
    print("\n检查静态文件...")
    
    static_files = [
        "static/css/style.css",
        "static/js/app.js"
    ]
    
    missing_files = []
    for file_path in static_files:
        if os.path.exists(file_path):
            print(f"[OK] {file_path}")
        else:
            print(f"[ERROR] {file_path} (未找到)")
            missing_files.append(file_path)
    
    if missing_files:
        print(f"\n[ERROR] 缺少 {len(missing_files)} 个静态文件")
        return False
    else:
        print(f"\n[OK] 所有静态文件都存在")
        return True

def check_dependencies():
    """检查依赖"""
    print("\n检查依赖...")
    
    required_modules = [
        ("fastapi", "fastapi"),
        ("uvicorn", "uvicorn"), 
        ("jinja2", "jinja2"),
        ("sqlalchemy", "sqlalchemy"),
        ("pydantic", "pydantic"),
        ("passlib", "passlib"),
        ("python-jose", "jose"),
        ("bcrypt", "bcrypt")
    ]
    
    missing_modules = []
    for module_name, import_name in required_modules:
        try:
            __import__(import_name)
            print(f"[OK] {module_name}")
        except ImportError:
            print(f"[ERROR] {module_name} (未安装)")
            missing_modules.append(module_name)
    
    if missing_modules:
        print(f"\n[ERROR] 缺少 {len(missing_modules)} 个依赖模块")
        print("请运行: pip install " + " ".join(missing_modules))
        return False
    else:
        print(f"\n[OK] 所有依赖都存在")
        return True

def main():
    print("MinerU 文档解析系统 - Web界面验证")
    print("=" * 50)
    
    # 检查依赖
    deps_ok = check_dependencies()
    
    # 检查路由
    routes_ok = check_routes()
    
    # 检查模板
    templates_ok = check_templates()
    
    # 检查静态文件
    static_ok = check_static_files()
    
    print("\n" + "=" * 50)
    if deps_ok and routes_ok and templates_ok and static_ok:
        print("[OK] Web界面验证通过！")
        print("\n启动命令:")
        print("  python start_web.py")
        print("\n访问地址:")
        print("  http://localhost:8000/web/")
        print("\n测试账户:")
        print("  用户: testuser / testpass123")
        print("  管理员: admin / admin123")
        return True
    else:
        print("[ERROR] Web界面验证失败！")
        return False

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)